package com.ayuan.blog.controller;

import com.ayuan.blog.bean.CommonResponseBean;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Created by xiaozhu on 16/8/13.
 */
@Controller
@Log4j2
public class ImageUploadController extends BaseController {

    @Autowired
    private ServletContext servletContext;

    private final static String ROOT = "/data/image/";

    @RequestMapping(value = "/uploadImage", method = RequestMethod.GET)
    public ModelAndView uploadImage() {
        return new ModelAndView("/uploadImage");
    }

    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public Object doUploadImage(@RequestParam("image") MultipartFile image) {
        if (!image.isEmpty()) {
            try {
                Files.copy(image.getInputStream(), Paths.get(ROOT, image.getOriginalFilename()));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                return new CommonResponseBean<Object>(1, "upload image failed, cause : " + e.getMessage(), null);
            }
        } else {
            return new CommonResponseBean<Object>(1, "upload image failed, cause : empty image", null);
        }
        return new CommonResponseBean<Object>("/image/" + image.getOriginalFilename());
    }

    @RequestMapping(value = "/image/{id}", method = RequestMethod.GET)
    public void image(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") String id) throws IOException {
        InputStream in = new FileInputStream(ROOT + request.getRequestURI().split("/image/")[1]);
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        IOUtils.copy(in, response.getOutputStream());
    }
}
